<template>
    <div class="user">
        <div class="top">
            <el-form :inline="true">
                <el-form-item label="用户名">
                    <el-input placeholder="请你输入搜索用户名" v-model="keywords"></el-input>
                </el-form-item>
            </el-form>
            <div class="operate">
                <el-button type="primary" icon="search" @click="handleSearch">查询</el-button>
                <el-button type="primary" icon="refresh" @click="handleReset">重置</el-button>
            </div>
        </div>
        <div class="content">
            <el-button type="primary" icon="plus" @click="handleAddUser">添加用户</el-button>
            <el-button type="danger" icon="delete" @click="handleDeleteBatch">批量删除</el-button>

            <el-table
                border
                class="table"
                :data="records"
                show-overflow-tooltip
                @selection-change="handleSelectionChange"
            >
                <el-table-column label="#" align="center" type="selection" />
                <el-table-column label="#" align="center" type="index" />
                <el-table-column label="ID" align="center" prop="id" />
                <el-table-column label="用户名" align="center" prop="name" />
                <el-table-column label="用户昵称" align="center" prop="username" />
                <el-table-column label="用户角色" align="center" prop="roleName" />
                <el-table-column label="创建时间" align="center" prop="createTime" />
                <el-table-column label="更新时间" align="center" prop="updateTime" />
                <el-table-column label="操作" align="center" width="300">
                    <template #default="{ row }">
                        <el-button
                            size="small"
                            type="primary"
                            icon="user"
                            @click="handleAssignRole(row)"
                        >
                            分配角色
                        </el-button>
                        <el-button
                            size="small"
                            type="primary"
                            icon="edit"
                            @click="handleEditUser(row)"
                        >
                            编辑
                        </el-button>
                        <el-popconfirm
                            width="250px"
                            :title="`您确定要删除用户${row.name}吗？`"
                            @confirm="handleDeleteUser(row)"
                        >
                            <template #reference>
                                <el-button size="small" type="danger" icon="delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                v-model:current-page="page"
                v-model:page-size="size"
                :page-sizes="[3, 5, 7, 9]"
                background
                layout="prev, pager, next, jumper,->,sizes,total"
                :total="total"
                @current-change="getUserList"
                @size-change="handleSizeChange"
            />

            <el-drawer direction="rtl" v-model="saveDrawer">
                <template #header>
                    <h4>{{ saveUserData.id ? '编辑用户' : '添加用户' }}</h4>
                </template>
                <template #default>
                    <div>
                        <el-form :model="saveUserData" ref="saveFormRef" :rules="saveUserRules">
                            <el-form-item label="用户姓名" prop="name">
                                <el-input
                                    v-model="saveUserData.name"
                                    placeholder="请输入用户名"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="用户昵称" prop="username">
                                <el-input
                                    v-model="saveUserData.username"
                                    placeholder="请输入用户昵称"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="用户密码" prop="password" v-if="!saveUserData.id">
                                <el-input
                                    v-model="saveUserData.password"
                                    placeholder="请输入用户密码"
                                ></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="handleSaveUserCancel">取消</el-button>
                        <el-button type="primary" @click="handleSaveUserConfirm">确定</el-button>
                    </div>
                </template>
            </el-drawer>

            <el-drawer direction="rtl" v-model="roleDrawer">
                <template #header>
                    <h4>分配角色(职位)</h4>
                </template>
                <template #default>
                    <div>
                        <el-form>
                            <el-form-item label="用户名称">
                                <el-input v-model="saveUserData.name" :disabled="true"></el-input>
                            </el-form-item>
                            <el-form-item label="用户职位">
                                <el-checkbox
                                    v-model="checkAll"
                                    :indeterminate="isIndeterminate"
                                    @change="handleCheckAllChange"
                                >
                                    全选
                                </el-checkbox>
                                <el-checkbox-group
                                    v-model="assignRoles"
                                    @change="handleCheckedRolesChange"
                                >
                                    <el-checkbox
                                        v-for="role in roleList"
                                        :key="role.id"
                                        :value="role"
                                    >
                                        {{ role.roleName }}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="roleDrawer = false">取消</el-button>
                        <el-button type="primary" @click="handleAssignRoleConfirm">确定</el-button>
                    </div>
                </template>
            </el-drawer>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useSettingStore } from '@/store/modules/setting'
import {
    reqUserInfo,
    reqAddOrUpdateUser,
    reqAllRole,
    reqSetUserRole,
    reqRemoveUser,
    reqSelectUser,
} from '@/api/acl/user'

const page = ref<number>(1)
const size = ref<number>(3)
const total = ref<number>(0)
const records = ref<any[]>([])

const keywords = ref<string>('')

const saveDrawer = ref<boolean>(false)
const roleDrawer = ref<boolean>(false)

const settingStore = useSettingStore()

const getUserList = async (p: number = 1) => {
    page.value = p
    let result: any = await reqUserInfo(page.value, size.value, keywords.value)
    if (result.code === 200) {
        records.value = result.data.records
        total.value = result.data.total
    }
}

const handleSizeChange = () => {
    getUserList()
}

onMounted(() => {
    getUserList()
})

const saveUserData = ref<any>({
    id: 0,
    name: '',
    username: '',
    password: '',
})

const handleSaveUserCancel = () => {
    saveDrawer.value = false
}

const handleSaveUserConfirm = async () => {
    await saveFormRef.value.validate()

    let result = await reqAddOrUpdateUser(saveUserData.value)
    if (result.code === 200) {
        let msg = saveUserData.value.id ? '更新成功' : '添加成功'
        ElMessage.success(msg)
        // getUserList(saveUserData.value.id ? page.value : 1)
        //浏览器自动刷新一次 防止更新的是当前用户
        window.location.reload()
    } else {
        let msg = saveUserData.value.id ? '更新失败' : '添加失败'
        ElMessage.error(msg)
        return
    }

    saveDrawer.value = false
}

const saveFormRef = ref()

const validateName = (_rule: any, value: string, callback: any) => {
    if (value.length < 3) {
        callback(new Error('用户姓名不能少于3个字符'))
    } else {
        callback()
    }
}

const validateUsername = (_rule: any, value: string, callback: any) => {
    if (value.length < 3) {
        callback(new Error('用户昵称不能少于3个字符'))
    } else {
        callback()
    }
}

const validatePassword = (_rule: any, value: string, callback: any) => {
    if (value.length < 6) {
        callback(new Error('用户密码不能少于6个字符'))
    } else {
        callback()
    }
}

const saveUserRules = {
    name: [{ validator: validateName, trigger: 'blur' }],
    username: [{ validator: validateUsername, trigger: 'blur' }],
    password: [{ validator: validatePassword, trigger: 'blur' }],
}

const handleEditUser = (row: any) => {
    saveDrawer.value = true
    saveFormRef.value?.clearValidate()
    Object.assign(saveUserData.value, row)
}

const handleAddUser = () => {
    saveDrawer.value = true
    saveFormRef.value?.clearValidate()
    Object.assign(saveUserData.value, {
        id: 0,
        name: '',
        username: '',
        password: '',
    })
}

const checkAll = ref(false)
const isIndeterminate = ref(true)
const assignRoles = ref<any>([])
let roleList: any[] = []

const handleAssignRole = async (row: any) => {
    roleDrawer.value = true
    let result: any = await reqAllRole(row.id)
    if (result.code === 200) {
        roleList = result.data.allRolesList
        assignRoles.value = result.data.assignRoles
    }
    Object.assign(saveUserData.value, row)
}

const handleCheckAllChange = (val: any) => {
    assignRoles.value = val ? roleList : []
    isIndeterminate.value = false
}

const handleCheckedRolesChange = (value: any) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === roleList.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < roleList.length
}

const handleAssignRoleConfirm = async () => {
    let data: any = {
        userId: saveUserData.value.id,
        roleIds: assignRoles.value.map((item: any) => item.id),
    }

    let result = await reqSetUserRole(data)
    if (result.code === 200) {
        ElMessage.success('分配成功')
        getUserList(page.value)
        roleDrawer.value = false
    }
}

const handleDeleteUser = async (row: any) => {
    let result = await reqRemoveUser(row.id)
    if (result.code === 200) {
        ElMessage.success('删除成功')
        getUserList()
    }
}

const selectIdArr = ref<number[]>([])
const handleSelectionChange = async (val: any) => {
    selectIdArr.value = val
}
const handleDeleteBatch = async () => {
    if (selectIdArr.value.length === 0) {
        ElMessage.error('请选择要删除的用户')
        return
    }
    let ids: number[] = selectIdArr.value.map((item: any) => item.id)
    let result: any = await reqSelectUser(ids)
    if (result.code === 200) {
        ElMessage.success('删除成功')
        getUserList()
    } else {
        ElMessage.error('删除失败')
    }
}

const handleSearch = () => {
    getUserList()
    keywords.value = ''
}

const handleReset = () => {
    settingStore.refreshPage = !settingStore.refreshPage
}
</script>

<style lang="scss" scoped>
.user {
    .top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        border-bottom: 1px solid #e4e7ed;
    }

    .content {
        .table {
            margin: 20px 0;
        }
    }
}
</style>
